package com.matrix.im.netty.session;

import com.matrix.common.enums.UserTypeEnum;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 有点甜
 * @since 2025/8/6
 */
@Component
public class SessionManager {

    public static final AttributeKey<Long> USER_ID_KEY = AttributeKey.valueOf("userId");
    public static final AttributeKey<UserTypeEnum> USER_TYPE_KEY = AttributeKey.valueOf("userType");

    private final Map<Long, Channel> userChannelMap = new ConcurrentHashMap<>();

    public void bindSession(Long userId, UserTypeEnum userType, Channel channel) {
        userChannelMap.put(userId, channel);
        channel.attr(USER_ID_KEY).set(userId);
        channel.attr(USER_TYPE_KEY).set(userType);
    }

    public void unbindSession(Channel channel) {
        Long userId = channel.attr(USER_ID_KEY).get();
        if (userId != null) {
            userChannelMap.remove(userId);
        }
    }

    public Channel getChannel(Long userId) {
        return userChannelMap.get(userId);
    }
}
